package smartcase.base.file;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Component;
import smartcase.base.func.ThrowingFunc;
import smartcase.base.func.ThrowingSupplier;
import smartcase.config.cos.CosConfiguration;
import smartcase.errors.CosException;
import smartcase.errors.Errors;

import java.io.InputStream;
import java.net.URL;

@Component
public class TencentCosTool {

  private COSClient cosClient;

  public TencentCosTool(CosConfiguration cfg) {
    if (cfg != null) {
      COSCredentials cred = new BasicCOSCredentials(cfg.getSecretId(), cfg.getSecretKey());
      Region region = new Region(cfg.getRegion());
      ClientConfig clientConfig = new ClientConfig(region);
      clientConfig.setHttpProtocol(HttpProtocol.https);
      cosClient = new COSClient(cred, clientConfig);
    }
  }

  public void uploadFile(String bucketName, String key, InputStream input, ObjectMetadata meta) {
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, input, meta);
    Errors.map(
            () -> {
              cosClient.putObject(putObjectRequest);
            })
        .orElseThrow()
        .handFinally();
  }

  public URL getObjectAccessURL(String bucketName, String key) {
    return Errors.map(() -> cosClient.getObjectUrl(bucketName, key)).orElseThrow().handFinally();
  }
}
